package com.wh.service.impl;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.wh.service.IExt.ICustomFormService;
import com.legend.utils.*;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.tags.InputTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.wh.beans.custom.ICustomLabel;
import com.wh.beans.custom.LabelInst;
import com.wh.beans.custom.LabelType;
import com.wh.dao.BaseDao;
import com.wh.dao.ext.CustomFieldDao;
import com.wh.dao.ext.CustomFormDao;
import com.wh.model.BaseModel;
import com.wh.model.CustomField;
import com.wh.model.CustomForm;

/*
 *author:徐洪昌
 *blog:http://cnblogs.com/xusir
 *datetime:2014-03-27 23:25:37
 */
public class CustomFormService extends BaseServiceImp implements ICustomFormService {

	Logger log = Logger.getRootLogger();
    private CustomFormService() {
    }

    //volatile修饰的写变量不能和之前的读写代码调整，读变量不能和之后的读写代码调整
    private volatile static ICustomFormService instance = null;

    /**
     * 单例
     *
     * @return
     */
    public static ICustomFormService getInstance() {
        if (instance == null) {
            synchronized (ICustomFormService.class) {
                if (instance == null) {
                    instance = new CustomFormService();
                }
            }
        }
        return instance;
    }
	/**
	 * 批量删除数据
	 */
	public ReturnResult delByIds(String ids) {
		SqlSession session = getSqlSession();
		ReturnResult result = new ReturnResult();
		try {
			CustomFormDao dao = session.getMapper(CustomFormDao.class);
			result = delByMap(dao, ids);
		} catch (Exception ex) {
			log.error(ex.getMessage());
		} finally {
			session.close();
		}
		return result;
	}

	/**
	 * 分页数据查询
	 * 
	 * @param pageIndex
	 * @param pageSize
	 * @param map
	 * @return
	 */
	public ReturnResult selectByMap(int pageIndex, int pageSize, Map<String, Object> map) {
		SqlSession session = getSqlSession();
		CustomFormDao dao = session.getMapper(CustomFormDao.class);
		int recordNum = (pageIndex - 1) * pageSize;
		List<CustomForm> lst = session.selectList(ConfigUtils.getInstance().getDaoPackage(".CustomFormDao.selectByMap"), map,
				new RowBounds(recordNum, pageSize));
		int total = dao.count(map);
		ReturnResult result = new ReturnResult();
		result.setMsg(i18nUtils.getVal("100001000"));
		result.setRows(lst);
		result.setTotal(total);
		result.setStatus(Status.SUCCESS);
		session.close();
		return result;
	}

	@Override
	public ReturnResult insertByModel(BaseModel model) {
		SqlSession session = getSqlSession();
		CustomFormDao dao = session.getMapper(CustomFormDao.class);
		CustomForm form = (CustomForm) model;
		ReturnResult result = new ReturnResult();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dbtableName", form.getDbtableName());
		Integer count = dao.count(map);
		if (count != null && count > 0) {
			result.setStatus(Status.ERROR);
			result.setMsg(i18nUtils.getVal("400001001"));
		} else {

			int i = dao.insertByModel(model);
			if (i == 1) {
				Map<String, String> tableMap = new HashMap<String, String>();
				tableMap.put("tableName", form.getDbtableName());
				tableMap.put("tableNote", form.getFormRemark());
				try {
					dao.createTable(tableMap);
				} catch (Exception e) {
					dao.delByMap(map);
				}

				result.setStatus(Status.SUCCESS);
				result.setMsg(i18nUtils.getVal("100001000"));
			}
		}
		session.close();
		return result;
	}

	@Override
	public ReturnResult editByModel(BaseModel model) {
		SqlSession session = getSqlSession();
		CustomFormDao dao = session.getMapper(CustomFormDao.class);
		ReturnResult result = editByModel(dao, model);
		session.close();
		return result;
	}

	/**
	 * 根据ID获取一条数据
	 * 
	 * @param id
	 * @return
	 */
	public ReturnResult selectById(String id) {
		SqlSession session = getSqlSession();
		ReturnResult result = new ReturnResult();
		result.setStatus(Status.ERROR);
		BaseDao dao = session.getMapper(CustomFormDao.class);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<CustomForm> lst = dao.selectByMap(map);
		if (lst.size() == 1) {
			result.setData(lst.get(0));
			result.setStatus(Status.SUCCESS);
		} else {
			result.setMsg(i18nUtils.getVal("100004000"));
		}
		session.close();
		return result;
	}

	/**
	 * 批量审核数据
	 * 
	 */
	public ReturnResult audit(int state, String[] idArr) {
		SqlSession session = getSqlSession();
		CustomFormDao dao = session.getMapper(CustomFormDao.class);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("idArr", idArr);
		map.put("state", state);
		Integer num = dao.audit(map);
		ReturnResult result = new ReturnResult();
		if (num > 0) {
			result.setMsg(i18nUtils.getVal("100001000"));
			result.setStatus(Status.SUCCESS);
		}
		session.close();
		return result;
	}

	/**
	 * 排序
	 * 
	 * @param sorts
	 * @param ids
	 * @return
	 */
	public ReturnResult sort(String sorts, String ids) {
		ReturnResult result;
		SqlSession session = getSqlSession();
		CustomFormDao dao = session.getMapper(CustomFormDao.class);
		result = sort(session, dao, sorts, ids);
		if (session != null)
			session.close();
		return result;
	}

	/*
	 * 编辑表单写入文件
	 */
	public ReturnResult editorForm(String formGuid, String content, HttpServletRequest request) {
		ReturnResult result = new ReturnResult();

		String filePath = "/template/custom/";
		String absolutePath = request.getSession().getServletContext().getRealPath(filePath);
		try {
			FileUtils.writeFile(absolutePath + "/" + formGuid + ".txt", content);
		} catch (FileNotFoundException e) {
			log.error(e.getMessage());
			result.setMsg(i18nUtils.getVal("100002000"));
			result.setStatus(Status.EXCEPTION);
			return result;
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			result.setMsg(i18nUtils.getVal("100002000"));
			result.setStatus(Status.EXCEPTION);
			return result;
		}
		content = Base64.encodereplace(content);
		content = new String(Base64.decode(content.toCharArray()));
		String addStr = content, editStr = content;
		SqlSession session = getSqlSession();
		CustomFieldDao dao = session.getMapper(CustomFieldDao.class);
		CustomField field = new CustomField();
		field.setFormGuid(formGuid);
		List<CustomField> fields = dao.selectByModel(field);
		session.close();
		if (fields.size() > 0) {
			Parser parser;
			try {
				parser = new Parser(content);
				NodeFilter filter = new HasAttributeFilter("type", "image");
				NodeFilter filter2 = new HasAttributeFilter("class");
				NodeList nodes = parser.extractAllNodesThatMatch(filter).extractAllNodesThatMatch(filter2);
				for (int i = 0; i < nodes.size(); i++) {
					Node node = (Node) nodes.elementAt(i);
					if (node instanceof InputTag) {
						InputTag tag = (InputTag) nodes.elementAt(i);
						String id = tag.getAttribute("id");
						if (!StringUtils.isEmpty(id))
							for (CustomField customField : fields) {
								if (id.equalsIgnoreCase(customField.getFieldDbName())) {
									ICustomLabel label = LabelInst.getLabel(customField.getFieldType());
									if (label != null) {
										String tagStr = node.toHtml(true);
										addStr = addStr.replace(tagStr, label.getCustomLabel(customField, LabelType.add));
										editStr = editStr.replace(tagStr, label.getCustomLabel(customField, LabelType.edit));
									} else {
										result.setMsg(i18nUtils.getVal("400001003") );
										result.setStatus(Status.ERROR);
										return result;
									}
								}
							}
					}
				}
				try {
					FileUtils.writeFile(absolutePath + "/" + formGuid + "/add.flt", addStr);
					FileUtils.writeFile(absolutePath + "/" + formGuid + "/edit.flt", editStr);
					result.setMsg(i18nUtils.getVal("100001000"));
					result.setStatus(Status.SUCCESS);
				} catch (UnsupportedEncodingException e) {
					log.error(e.getMessage());
					result.setMsg(i18nUtils.getVal("100002000"));
					result.setStatus(Status.EXCEPTION);
				} catch (FileNotFoundException e) {
					log.error(e.getMessage());
					result.setMsg(i18nUtils.getVal("100002000"));
					result.setStatus(Status.EXCEPTION);
				}
			} catch (ParserException e) {
				log.error(e.getMessage());
				result.setMsg(i18nUtils.getVal("100002000"));
				result.setStatus(Status.EXCEPTION);
			}
		}
		return result;
	}

}
